<!-- 多选题 -->
<template>
  <el-row>
    <!-- 题目 -->
    <el-row id="row1">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.question')">
          <richTextCom v-model="questionGroup" :group="questionGroup"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 选项个数 -->
    <el-row>
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.optionCount')">
          <optionChooseCom v-model="chooseOption" :option-array="optionArray"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 选项内容 -->
    <el-row>
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.optionContent')">
          <div class="contentList">
            <template v-for="(item, index) in optionGroupArray">
              <el-checkbox-group v-model="answerCheckboxGroup" @change="answerCheckboxGroupChange">
                <div v-for="(optionItem, optionIndex) in item.option" :id="'content-item-' + optionIndex" class="question-content-item">
                  <div class="item-left">
                    <h1>{{ optionItem.optionKey }}</h1>
                    <el-checkbox :label="optionItem.optionKey" border></el-checkbox>
                  </div>
                  <div class="item-right">
                    <richTextCom v-model="optionGroupArray[index].option[optionIndex]" :group="optionGroupArray[index].option[optionIndex]"/>
                  </div>
                </div>
              </el-checkbox-group>
            </template>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 参考答案 -->
    <el-row>
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.referAnswer')">
          <span class="refer-answer">{{ answerCheckboxGroup.join(',') }}</span>
          <label>(*请按正确顺序点击以上选项，以设置正确选项)</label>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 解析 -->
    <el-row id="row6">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.analysis')">
          <richTextCom v-model="analysisGroup" :group="analysisGroup"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 添加标签 -->
    <el-row id="row5">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.addTags')">
          <paperTagsCom ref="tags" v-model="chooseTags" :qId="qId" :show-btn="false"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 操作按钮 -->
    <div class="form-footer">
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="savePaperQuestion(1)">{{ $t('form.save') }}</el-button>
        <el-button v-if="!isEdit" type="primary" @click="savePaperQuestion(2)">{{ $t('paperQuestionLangList.goOnAddQuestion') }}</el-button>
      </el-row>
    </div>
  </el-row>
</template>

<script>
  import richTextCom from './richText'
  import optionChooseCom from './optionChoose'
  import paperTagsCom from '../paperTags'
  import { createdQuestion, getQuestionDetail, getPaperQuestionTags, updateQuestion } from '@/api/question'
  import { updatePaperQuestion } from '@/api/paper'
  export default {
    name: 'Sorting',
    components: {
      richTextCom,
      optionChooseCom,
      paperTagsCom
    },
    props: {
      // 试卷id
      parentPaperId: String,
      newEditType: String,
      categoryProps: {
        type: String,
        default: 'sorting'
      }
    },
    data() {
      return {
        chooseOption: 4,
        // 选项个数
        optionArray: [2, 3, 4, 5, 6, 7],
        // 题目文本信息
        questionGroup: {
          category: '',
          subjectTxt: '',
          subjectAudio: ''
        },
        // 选项内容文本信息数组
        optionGroupArray: [],
        // 字母数组
        letterArray: [],
        // 解析
        analysisGroup: {
          category: '',
          subjectTxt: '',
          subjectAudio: ''
        },
        // 正确答案
        answerCheckboxGroup: [],
        // 选择的标签
        chooseTags: [],
        // 是否可提交标志
        submitFlag: false,
        qId: '',
        isEdit: false
      }
    },
    watch: {
      // 监听选项个数改变
      'chooseOption': function(val) {
        this.initOption()
        console.info(val)
      },
      // 监听标签选择
      'chooseTags': function(val) {
        console.info(val)
      }
    },
    created() {
      console.info(this.parentPaperId)
      this.initPage()
    },
    methods: {
      // 初始化页面
      initPage() {
        this.questionGroup.category = this.categoryProps
        this.analysisGroup.category = this.categoryProps
        this.initOption()
      },
      // 初始化选项内容
      initOption() {
        this.optionGroupArray = []
        const optionArray = []
        const letterArray = []
        // 选项内容
        for (let i = 0; i < this.chooseOption; i++) {
          const letter = String.fromCharCode(i + 65)
          letterArray.push(letter)
          const obj = {
            optionTxt: '',
            optionAudio: '',
            optionKey: letter
          }
          optionArray.push(obj)
        }
        const obj = {
          subjectTxt: '',
          subjectAudio: '',
          analysisTxt: '',
          analysisAudio: '',
          answerKey: letterArray[0],
          option: optionArray
        }
        this.optionGroupArray.push(obj)
      },
      // 初始化数据
      initData() {
        this.chooseOption = 4
        this.questionGroup = {
          category: 'sorting',
          subjectTxt: '',
          subjectAudio: ''
        }
        this.optionGroupArray = []
        this.initOption()
        this.letterArray = []
        this.analysisGroup = {
          category: 'sorting',
          subjectTxt: '',
          subjectAudio: ''
        }
        this.answerCheckboxGroup = []
        this.chooseTags = []
        this.submitFlag = false
        this.qId = ''
        this.isEdit = false
        this.$refs.tags.initPage()
      },
      // 编辑时加载数据
      initUpdateData(row) {
        const _this = this
        _this.isEdit = true
        const loading = _this.$loading({
          lock: true,
          text: '数据加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        getQuestionDetail(row.id).then(res => {
          loading.close()
          if (res) {
            res.questions.forEach(v => {
              v.option = v.options
            })
            _this.optionGroupArray = res.questions
            _this.questionGroup.subjectTxt = res.groupSubjectTxt
            _this.questionGroup.category = res.category
            _this.questionGroup.subjectAudio = res.groupSubjectAudio
            _this.analysisGroup.subjectTxt = res.questions[0].analysisTxt
            _this.answerCheckboxGroup = res.questions[0].answerKey.split(',')
            _this.qId = row.id
          }
        }).catch(err => {
          loading.close()
          console.info(err)
        })
      },
      // 多选选择事件
      answerCheckboxGroupChange(val) {
        // val.sort()
      },
      // 表单验证
      formValidator() {
        if (this.questionGroup.subjectTxt.trim() === '') {
          this.$message({
            message: '请填写题目信息',
            type: 'warning'
          })
          document.getElementById('row1').scrollIntoView()
          return
        }
        if (this.chooseTags.length === 0) {
          this.$message({
            message: '请选择至少一个标签',
            type: 'warning'
          })
          document.getElementById('row5').scrollIntoView()
          return
        }
        if (this.answerCheckboxGroup.length < 2) {
          this.$message({
            message: '请设置正确答案',
            type: 'warning'
          })
          return
        }
        // 选项内容填写数组
        const optionContent = this.optionGroupArray
        let idx = ''
        for (let i = 0; i < optionContent.length; i++) {
          for (let j = 0; j < optionContent[i].option.length; j++) {
            if (optionContent[i].option[j].optionTxt.trim() === '') {
              idx = j
              break
            }
          }
        }
        if (idx !== '') {
          this.$message({
            message: '请填写所有答案选项',
            type: 'warning'
          })
          document.getElementById('content-item-' + idx).scrollIntoView()
          return
        }
        this.submitFlag = true
      },
      // 保存
      savePaperQuestion(type) {
        const _this = this
        _this.formValidator()
        // 执行保存
        if (_this.submitFlag) {
          /* 构造FormData键值question的数据 */
          _this.optionGroupArray.forEach(v => {
            v.subjectTxt = _this.questionGroup.subjectTxt
            v.subjectAudio = _this.questionGroup.subjectAudio
            v.analysisTxt = _this.analysisGroup.subjectTxt
            v.analysisAudio = _this.analysisGroup.subjectAudio
            v.answerKey = _this.answerCheckboxGroup.join(',')
          })
          /* end */
          // 提交数据
          const postData = {
            group: JSON.stringify(_this.questionGroup),
            labelIds: _this.chooseTags.join(','),
            category: _this.categoryProps,
            question: JSON.stringify(_this.optionGroupArray)
          }
          const loading = _this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.6)'
          })
          // 新增
          if (!_this.isEdit) {
            createdQuestion(postData).then(res => {
              if (res) {
                if (_this.newEditType == 'question') {
                  loading.close()
                  // 保存
                  if (type == 1) {
                    _this.$emit('saveCallback')
                  }
                  // 继续录题
                  else if (type == 2) {
                    _this.initData()
                  }
                } else {
                  const questionId = res.id
                  const postData2 = {
                    questionIds: questionId
                  }
                  // 更新试卷下的试题
                  updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                    _this.$message({
                      message: '保存成功',
                      type: 'success'
                    })
                    loading.close()
                    // 保存
                    if (type == 1) {
                      _this.$emit('saveCallback')
                    }
                    // 继续录题
                    else if (type == 2) {
                      _this.initData()
                    }
                  }).catch(err => {
                    loading.close()
                    console.info(err)
                  })
                }
              }
            }).catch(err => {
              loading.close()
              console.info(err)
            })
          }
          // 编辑
          else {
            if (_this.newEditType == 'question') {
              postData._method = 'PUT'
              updateQuestion(_this.qId, postData).then(res => {
                _this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                loading.close()
                // 保存
                if (type == 1) {
                  _this.$emit('saveCallback')
                }
                // 继续录题
                else if (type == 2) {
                  _this.initData()
                }
              }).catch(err => {
                loading.close()
                console.info(err)
              })
            } else {
              postData._method = 'PUT'
              updateQuestion(_this.qId, postData).then(res => {
                if (res) {
                  const questionId = res.id
                  const postData2 = {
                    questionIds: questionId
                  }
                  // 更新试卷下的试题
                  updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                    _this.$message({
                      message: '保存成功',
                      type: 'success'
                    })
                    loading.close()
                    // 保存
                    if (type == 1) {
                      _this.$emit('saveCallback')
                    }
                    // 继续录题
                    else if (type == 2) {
                      _this.initData()
                    }
                  }).catch(err => {
                    loading.close()
                    console.info(err)
                  })
                }
              })
            }
          }
        }
      }
    }
  }
</script>
